import request from '@/utils/request'

export interface MenuCreateData {
  name: string
  icon: string
  parent_id?: any
  description?: string
}

export interface MenuUpdateData {
  name?: string
  path?: string
  icon?: string
  parent_id?: any
  component_name?: string
  permission_code?: string
  description?: string
  sort_weight?: number
  is_enabled?: boolean
}

export interface MenuOrderItem {
  id: number
  sort_weight: number
  parent_id?: any
}

export interface ApiResponse<T = any> {
  success: boolean
  message?: string
  data?: T
  errors?: any
}

/**
 * 动态菜单管理API
 */
export const dynamicMenuApi = {
  /**
   * 获取菜单树结构
   */
  async getMenuTree(): Promise<ApiResponse> {
    try {
      const response = await request.get('/api/dynamic-menus/tree/')
      return response.data
    } catch (error) {
      console.error('获取菜单树失败:', error)
      throw error
    }
  },

  /**
   * 创建新菜单
   */
  async createMenu(data: MenuCreateData): Promise<ApiResponse> {
    try {
      const response = await request.post('/api/dynamic-menus/create-menu/', data)
      return response.data
    } catch (error) {
      console.error('创建菜单失败:', error)
      throw error
    }
  },

  /**
   * 更新菜单
   */
  async updateMenu(id: number, data: MenuUpdateData): Promise<ApiResponse> {
    try {
      const response = await request.patch(`/api/dynamic-menus/${id}/`, data)
      return {
        success: true,
        data: response.data,
        message: '菜单更新成功'
      }
    } catch (error) {
      console.error('更新菜单失败:', error)
      throw error
    }
  },

  /**
   * 删除菜单（包含组件文件）
   */
  async deleteMenuWithComponent(id: number): Promise<ApiResponse> {
    try {
      const response = await request.delete(`/api/dynamic-menus/${id}/delete-with-component/`)
      return response.data
    } catch (error) {
      console.error('删除菜单失败:', error)
      throw error
    }
  },

  /**
   * 重新排序菜单
   */
  async reorderMenus(menuOrders: MenuOrderItem[]): Promise<ApiResponse> {
    try {
      const response = await request.post('/api/dynamic-menus/reorder/', {
        menu_orders: menuOrders
      })
      return response.data
    } catch (error) {
      console.error('菜单排序失败:', error)
      throw error
    }
  },

  /**
   * 获取可用图标列表
   */
  async getAvailableIcons(): Promise<ApiResponse> {
    try {
      const response = await request.get('/api/dynamic-menus/icons/')
      return response.data
    } catch (error) {
      console.error('获取图标列表失败:', error)
      throw error
    }
  },

  /**
   * 获取所有菜单（用于选择父菜单）
   */
  async getAllMenus(): Promise<ApiResponse> {
    try {
      const response = await request.get('/api/dynamic-menus/')
      return {
        success: true,
        data: response.data.results || response.data
      }
    } catch (error) {
      console.error('获取菜单列表失败:', error)
      throw error
    }
  },

  /**
   * 获取菜单详情
   */
  async getMenuDetail(id: number): Promise<ApiResponse> {
    try {
      const response = await request.get(`/api/dynamic-menus/${id}/`)
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取菜单详情失败:', error)
      throw error
    }
  },

  /**
   * 批量删除菜单
   */
  async batchDeleteMenus(ids: number[]): Promise<ApiResponse> {
    try {
      const deletePromises = ids.map(id => this.deleteMenuWithComponent(id))
      const results = await Promise.allSettled(deletePromises)

      const successCount = results.filter(result => result.status === 'fulfilled').length
      const failCount = results.length - successCount

      return {
        success: failCount === 0,
        message: `批量删除完成：成功 ${successCount} 个，失败 ${failCount} 个`,
        data: {
          total: results.length,
          success: successCount,
          fail: failCount
        }
      }
    } catch (error) {
      console.error('批量删除菜单失败:', error)
      throw error
    }
  },

  /**
   * 搜索菜单
   */
  async searchMenus(keyword: string): Promise<ApiResponse> {
    try {
      const response = await request.get('/api/dynamic-menus/', {
        params: { search: keyword }
      })
      return {
        success: true,
        data: response.data.results || response.data
      }
    } catch (error) {
      console.error('搜索菜单失败:', error)
      throw error
    }
  },

  /**
   * 导出菜单配置
   */
  async exportMenuConfig(): Promise<ApiResponse> {
    try {
      const response = await request.get('/api/dynamic-menus/tree/')
      if (response.data.success) {
        // 生成配置文件内容
        const configContent = this.generateMenuConfigFile(response.data.data)

        // 创建下载链接
        const blob = new Blob([configContent], { type: 'text/typescript' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'menus.ts'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)

        return {
          success: true,
          message: '菜单配置导出成功'
        }
      } else {
        throw new Error(response.data.message || '获取菜单数据失败')
      }
    } catch (error) {
      console.error('导出菜单配置失败:', error)
      throw error
    }
  },

  /**
   * 生成菜单配置文件内容
   */
  generateMenuConfigFile(menus: any[]): string {
    const generateMenuItems = (items: any[], indent = 0): string => {
      const spaces = '  '.repeat(indent)
      return items.map(item => {
        const children = item.children && item.children.length > 0
          ? `,\n${spaces}  children: [\n${generateMenuItems(item.children, indent + 2)}\n${spaces}  ]`
          : ''

        return `${spaces}{
${spaces}  id: '${item.id}',
${spaces}  name: '${item.name}',
${spaces}  path: '${item.path}',
${spaces}  icon: '${item.icon}',
${spaces}  component_name: '${item.component_name || ''}',
${spaces}  permission_code: '${item.permission_code || ''}',
${spaces}  sort_weight: ${item.sort_weight || 0},
${spaces}  is_generated: ${item.is_generated || false}${children}
${spaces}}`
      }).join(',\n')
    }

    return `// 自动生成的菜单配置文件
// 生成时间: ${new Date().toISOString()}

export interface MenuItem {
  id: string | number
  name: string
  path: string
  icon: string
  component_name?: string
  permission_code?: string
  sort_weight?: number
  is_generated?: boolean
  children?: MenuItem[]
}

export const STATIC_MENUS: MenuItem[] = [
${generateMenuItems(menus, 1)}
]

export default STATIC_MENUS`
  },

  /**
   * 同步静态配置文件
   */
  async syncStaticConfig(): Promise<ApiResponse> {
    try {
      const response = await request.post('/api/dynamic-menus/sync-static-config/')
      return response.data
    } catch (error) {
      console.error('同步静态配置失败:', error)
      throw error
    }
  },

  /**
   * 同步路由配置
   */
  async syncRouteConfig(): Promise<ApiResponse> {
    try {
      const response = await request.post('/api/dynamic-menus/sync-route-config/')
      return response.data
    } catch (error) {
      console.error('同步路由配置失败:', error)
      throw error
    }
  },

  /**
   * 完整同步（静态配置 + 路由 + 权限）
   */
  async fullSync(): Promise<ApiResponse> {
    try {
      const response = await request.post('/api/dynamic-menus/full-sync/')
      return response.data
    } catch (error) {
      console.error('完整同步失败:', error)
      throw error
    }
  }
}
